package com.ykdl.member.kid.util;


import java.io.File;
import java.util.Calendar;

import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;
import net.wxxr.http.util.Constants;
import oauth.signpost.http.HttpParameters;
import android.R.bool;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.ykdl.member.kid.R;
import com.ykdl.member.KidApp;
import com.ykdl.member.base.QLog;
import com.ykdl.member.base.service.DownloadAPK;
import com.ykdl.member.base.service.DownloadAPK.DownloadBinder;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.kid.beans.HomeMessageCount;
import com.ykdl.member.kid.beans.VersionUpgrade;
import com.ykdl.member.kid.gears.BaseScreen;
import com.ykdl.member.kid.gears.HomeActivity;
import com.ykdl.member.kid.widget.dialog.DialogCallBack;
import com.ykdl.member.kid.widget.dialog.DialogImpl;
import com.ykdl.member.kid.widget.dialog.IDialog;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;

public class VersionUdgrateUtil {
	private static final String PROMPT_UPDATE_DATE = "prompt_update_date_";
	private static SharedPreferences settings;
	private static SharedPreferences.Editor editor;
	private VersionUpgrade  versionUpgrade = null;
	private static Context  context;
	private DownloadBinder binder;
	private Calendar c;
	private BaseScreen baseScreen;
	private boolean from=false; //判定是否是从设置页调用的监测版本方法
	static{
		
			//初始化配置文件
			if (editor == null) {
				if (settings == null) {
					settings = KidApp.getInstance().getApplicationContext().getSharedPreferences("version", Context.MODE_PRIVATE);
					editor = settings.edit();
				} else {
					editor = settings.edit();
				}
			}
			
	}
	public  VersionUdgrateUtil(Context  context,boolean from1){
		this.context = context;
//		this.activity = (BaseScreen)context;
		from=from1;
		c = Calendar.getInstance();
	}
	/**
	 * 检测版本是否需要更新
	 */
	public  void checkVersionUdgrate(){
		getDataForVersionUpgrade();
	}
	
	/**
	 * 检测版本是否需要更新
	 */
	public  void checkVersionUdgrateForTime(){
		//获得提示更新时间(每三天进行检测一次，如有新版本进行更新。)
		long prompt_update_date = settings.getLong(PROMPT_UPDATE_DATE, 0);
		if(c.getTimeInMillis() > prompt_update_date){
			if(!isConnect())return;
				getDataForVersionUpgrade();
		}
	}
	/**
	 * 检测版本是否需要更新
	 */
	public  void checkVersionUdgrateForTime(boolean isSetting){
		//获得提示更新时间(每三天进行检测一次，如有新版本进行更新。)
			if(!isConnect())return;
				getDataForVersionUpgrade();
	}
	
	/**
	 * 网络获取版本号数据
	 */
	private  void getDataForVersionUpgrade() {
		final String url = KidConfig.BASE_CARD_SERVER + "/api/v1/application/version";
		HttpParameters  urlParams = new HttpParameters();
		urlParams.put("client_id", Constants.CLIENT_ID);
		urlParams.put("client_version", MobileUtils.getStringVersion()+"");
		request = Wxxr.getInstance().getRequest(url, urlParams);
		
		TaskManager.startHttpRequest(request, new ITag(){
			@Override
			public void refreshUI(Object t, DataState ds) {
				if(t != null){
					System.out.println("versionUpgrade : " + t);
					versionUpgrade = (VersionUpgrade)t;
					if(versionUpgrade.isExpired()){
						RequestAsAccessTokenUtil.getInstance(context).refreshTokenRequest(request, this, VersionUpgrade.class);
					}
					compareVersion(versionUpgrade);
				}
			}
			@Override
			public boolean refreshError(DataParseError parseError) {
				return true;
			}
			@Override
			public void refreshCancel() {
			}
		}, VersionUpgrade.class);//VersionUpgrade.class
	}
	
	/***
	 * 比较版本号
	 * @param version
	 */
	private void compareVersion(VersionUpgrade version){
		if (version.getLatest_version()!=null) {
			if(Float.parseFloat(MobileUtils.getStringVersion())<(version.getLatest_version().getVersion())){
				showUpdateDialog();
			}else {
				if(from){
					Toast.makeText(context, "已经是最新版本", 1).show();
				}
			}
		}else {
			Toast.makeText(context, "已经是最新版本", 1).show();
		}
		
		
	}
	
	/**
	 * 提示升级对话框
	 */
	private void showUpdateDialog() {
		DialogImpl  dialog = new DialogImpl();
		if(versionUpgrade.isForce_update()){//强制升级
			dialog.showDialog(context, "检测到新版本", "是否下载更新?", false, new DialogCallBack() {
				@Override
				public void onClick(int what) {
					switch (what) {
					case IDialog.YES://升级
						recoredCheckUpdateTime();
						commondDownlodTask();
						break;
					case IDialog.CANCLE://退出程序，强制升级
						KidApp.getInstance().getAppManager().AppExit(context, false);
						break;
					default:
						break;
					}
				}

			});
		}else{
			dialog.showDialog(context, "检测到新版本", "是否下载更新?", false, new DialogCallBack() {
				@Override
				public void onClick(int what) {
					switch (what) {
					case IDialog.YES://升级
						recoredCheckUpdateTime();
						commondDownlodTask();
						break;
					case IDialog.CANCLE://暂不升级
						recoredCheckUpdateTime();
						break;
					default:
						break;
					}
				}

			});
		}
	}
	 String url = null;
	 boolean isBinded = false;
	private void commondDownlodTask() {
		url = versionUpgrade.getLatest_version().getApp_url();
//		url = "http://bcscdn.baidu.com/new-repackonline/appsearch/AndroidPhone/1.0.21.64/1/1426l/appsearch_AndroidPhone_1-0-21-64_1426l.apk?response-content-disposition=attachment;filename=appsearch_AndroidPhone_1426l.apk&response-content-type=application/vnd.android.package-archive";
		if(url != null && !"".equals(url)){
			Intent intent = new Intent(KidApp.getInstance().getApplicationContext(), DownloadAPK.class);
			KidApp.getInstance().getApplicationContext().startService(intent);
			KidApp.getInstance().getApplicationContext().bindService(intent, conn, Context.BIND_AUTO_CREATE);
		}
	}
	
	/**
	 * //记录更新日期时间
	 */
	private void recoredCheckUpdateTime() {
		//每个三天提醒升级
		c.add(Calendar.DAY_OF_MONTH, 3);
		editor.putLong(PROMPT_UPDATE_DATE, c.getTimeInMillis());
		editor.commit();
	}
	ServiceConnection conn = new ServiceConnection() {
		@Override
		public void onServiceDisconnected(ComponentName name) {
			isBinded = false;
		}
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			binder = (DownloadBinder) service;
			isBinded = true;
			binder.start(url);
		}
	};
	private HttpBaseRequest request;
	
	
	public void cannelService(){
		if (isBinded) {
			KidApp.getInstance().getApplicationContext().unbindService(conn);
		}
		if (binder != null && binder.isDownLoading()) {
			binder.cancel();//取消下载
			Intent it = new Intent(KidApp.getInstance().getApplicationContext(), DownloadAPK.class);
			KidApp.getInstance().getApplicationContext().stopService(it);//停止服务
		}
	}
	public static boolean isConnect() {
		// 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
		try {
			ConnectivityManager connectivity = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			if (connectivity != null) {
				// 获取网络连接管理的对象
				NetworkInfo info = connectivity.getActiveNetworkInfo();
				if (info != null && info.isConnected()) {
					// 判断当前网络是否已经连接
					// if (info.getState() == NetworkInfo.State.CONNECTED) {
					return true;
					// }
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			QLog.debug("error", e.toString());
		}
		return false;
	}
}
